package com.tre.jdevtemplateboot.web.controller;

import com.tre.jdevtemplateboot.common.constant.SysConstantToken;
import com.tre.jdevtemplateboot.common.dto.PropertiesConfig;
import com.tre.jdevtemplateboot.common.dto.ResponseResult;
import com.tre.jdevtemplateboot.common.enums.AuthenticateTypeEnums;
import com.tre.jdevtemplateboot.common.jwt.IJwtTokenManagerService;
import com.tre.jdevtemplateboot.common.redis.IDataBaseAuthorizationService;
import com.tre.jdevtemplateboot.common.util.BasedDesUtils;
import com.tre.jdevtemplateboot.exception.business.SysInvalidUserException;
import com.tre.jdevtemplateboot.exception.business.SysRequestTokenCategoryException;
import com.tre.jdevtemplateboot.web.interceptor.HeadToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author JDev
 */
@RestController
@RequestMapping("/oauth")
public class OAuthController {

    @Autowired
    private IJwtTokenManagerService jwtTokenManagerService;
    @Autowired
    private PropertiesConfig propertiesVO;
    @Autowired(required = false)
    private IDataBaseAuthorizationService dataBaseAuthorizationService;


    /**
     * Refresh Token 签发
     *
     * @param userId
     * @param passWord
     * @param response
     * @return
     */
    @PostMapping("/refresh-token")
    public ResponseResult refreshToken(@RequestParam(value = "userId") String userId,
                                       @RequestParam(value = "password") String passWord,
                                       HttpServletResponse response) {
        if (!AuthenticateTypeEnums.JWT.toString().equalsIgnoreCase(propertiesVO.getTokenCategory())) {
            throw new SysRequestTokenCategoryException();
        }
        if (!StringUtils.hasLength(userId) || !StringUtils.hasLength(passWord)) {
            throw new SysInvalidUserException();
        }
        dataBaseAuthorizationService.checkLoginFromDbUserInfo(userId, passWord);
        String encoderUserId = BasedDesUtils.encryptBasedDes(userId);
        if (Long.parseLong(propertiesVO.getRefreshTokenExpire()) > 0) {
            String refreshToken = jwtTokenManagerService.generateRefreshToken(encoderUserId);
            response.setHeader(propertiesVO.getPreUserIssuer() + SysConstantToken.REFRESH_TOKEN_PRE, refreshToken);
        }
        String accessToken = jwtTokenManagerService.generateToken(encoderUserId);
        response.setHeader(propertiesVO.getPreUserIssuer() + SysConstantToken.SUFFIX_USER_ISSUER, accessToken);
        return ResponseResult.buildOK(encoderUserId);
    }

    /**
     * 根据RefreshToken 获取Access Token
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/access-token")
    public ResponseResult accessToken(HttpServletRequest request,
                                      HttpServletResponse response) {
        if (!AuthenticateTypeEnums.JWT.toString().equalsIgnoreCase(propertiesVO.getTokenCategory())) {
            throw new SysRequestTokenCategoryException();
        }
        String headerRefreshToken = null;
        if (StringUtils.hasLength(request.getHeader(propertiesVO.getAuthHeaderKey()))) {
            headerRefreshToken = HeadToken.getHeadToken(request, propertiesVO.getAuthHeaderKey(), propertiesVO.getAuthTypePrefix());
            if (!StringUtils.hasLength(headerRefreshToken)) {
                throw new SysInvalidUserException();
            }
        }
        String accessToken = jwtTokenManagerService.updateToken(headerRefreshToken);
        response.setHeader(propertiesVO.getPreUserIssuer() + SysConstantToken.SUFFIX_USER_ISSUER, accessToken);
        return ResponseResult.buildOK();
    }

}
